package com.example.interview.tread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

public class Test2 {

    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(2);
        final SynchronousQueue<String> queue = new SynchronousQueue<String>();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> { //主线程会先于子线程运行
                try {
                    semaphore.acquire();//设置路障
                    String input = queue.take();

//                    String output = TestDo.doSome(input);
                    try {
                        Thread.sleep(1000); //Semaphore让1每秒执行2个线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String output = input + "_" + (System.currentTimeMillis() / 1000);

                    System.out.println("--->"+Thread.currentThread().getName() + "-output-->" + output);
                    semaphore.release();//完成任务移除路障
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }).start();
        }

        //主线程生产数据
        System.out.println("begin:" + (System.currentTimeMillis() / 1000));
        for (int i = 0; i < 10; i++) {  //主线程put数据
            String input = i + "";  //
            try {
                queue.put(input);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
